/*
 * @Author: liu
 * @Date: 2024-02-26 20:37:32
 * @LastEditors: liu
 * @LastEditTime: 2024-03-05 23:16:06
 * @FilePath: \koa-pro\app\validator\validator.ts
 * @Description:
 * 天道酬勤
 */
import Schema, { Rules, Values } from 'async-validator'
import { Context } from 'koa'

/**
 * @description: 验证处理函数
 * @param {Context} ctx
 * @param {Rules} rules 验证规则
 * @param {Boolean} flag 设置错误显示规则，默认为显示第一个报错信息
 * @return {*}
 */
async function validate<T extends Values>(
  ctx: Context,
  rules: Rules,
  flag: Boolean = false
): Promise<{ data: T; error: any | null }> {
  //传入校验规则
  const validator = new Schema(rules)
  //data:具体的数据
  let data: any = {}

  switch (ctx.method) {
    case 'GET':
      break
    case 'POST':
      data = ctx.request.body
      console.log(data)
      break
    case 'DELETE':
      break
  }

  return await validator
    .validate(data)
    .then(() => {
      //验证通过的返回
      console.log('验证通过！')
      return {
        data: data as T,
        error: null
      }
    })
    .catch((err) => {
      if (flag) {
        return {
          data: {} as T,
          error: err
        }
      }
      return {
        data: {} as T,
        error: err.errors[0]
      }
    })
}

export default validate
